document.addEventListener('DOMContentLoaded', function() {
    // 加载用户列表
    loadUsers();
    // 加载系统设置
    loadSettings();

    // 绑定头像更换按钮点击事件
    document.getElementById('changeAvatarBtn').addEventListener('click', function() {
        document.getElementById('avatarInput').click();
    });

    // 绑定头像文件选择事件
    document.getElementById('avatarInput').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('avatarPreview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // 绑定用户表单提交事件
    document.getElementById('userForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData();
        formData.append('username', document.getElementById('userName').value);
        formData.append('gender', document.querySelector('input[name="gender"]:checked').value);
        formData.append('grade', document.getElementById('userGrade').value);
        
        // 添加头像文件
        const avatarFile = document.getElementById('avatarInput').files[0];
        if (avatarFile) {
            formData.append('avatar', avatarFile);
        }
        
        // 获取用户ID（如果是编辑模式）
        const userId = this.dataset.userId;
        
        saveUser(formData, userId);
    });

    // 绑定设置表单提交事件
    document.getElementById('apiForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = {
            api_key: document.getElementById('apiKey').value,
            api_model: document.getElementById('apiModel').value
        };
        saveSettings(formData);
    });

    // API Key 显示/隐藏切换
    document.getElementById('toggleApiKey').addEventListener('click', function() {
        const apiKeyInput = document.getElementById('apiKey');
        const icon = this.querySelector('i');
        if (apiKeyInput.type === 'password') {
            apiKeyInput.type = 'text';
            icon.className = 'fas fa-eye-slash';
        } else {
            apiKeyInput.type = 'password';
            icon.className = 'fas fa-eye';
        }
    });
});

// 加载用户列表
async function loadUsers() {
    try {
        const response = await fetch('/api/users');
        const result = await response.json();
        if (result.status === 'success') {
            renderUsers(result.data);
        }
    } catch (error) {
        console.error('Error loading users:', error);
        showToast('加载用户列表失败', 'error');
    }
}

// 加载系统设置
async function loadSettings() {
    try {
        const response = await fetch('/api/settings');
        const result = await response.json();
        if (result.status === 'success') {
            const settings = result.data;
            document.getElementById('apiKey').value = settings.api_key || '';
            document.getElementById('apiModel').value = settings.api_model || 'deepseek-chat';
        }
    } catch (error) {
        console.error('Error loading settings:', error);
        showToast('加载设置失败', 'error');
    }
}

// 保存用户信息
async function saveUser(formData, userId = null) {
    try {
        const method = 'POST';
        const url = userId ? `/api/users/${userId}` : '/api/users';
        
        const response = await fetch(url, {
            method: method,
            body: formData
        });
        
        const result = await response.json();
        if (result.status === 'success') {
            showToast('用户信息保存成功');
            loadUsers(); // 重新加载用户列表
            const modal = bootstrap.Modal.getInstance(document.getElementById('userEditModal'));
            modal.hide();
            
            // 重置表单和预览图
            const form = document.getElementById('userForm');
            form.reset();
            delete form.dataset.userId; // 清除用户ID
            document.getElementById('avatarPreview').src = '/static/images/avatar.png';
            document.getElementById('avatarInput').value = '';
        } else {
            showToast('保存失败：' + result.message, 'error');
        }
    } catch (error) {
        console.error('Error saving user:', error);
        showToast('保存用户信息失败', 'error');
    }
}

// 保存系统设置
async function saveSettings(settingsData) {
    try {
        const response = await fetch('/api/settings', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(settingsData)
        });
        
        const result = await response.json();
        if (result.status === 'success') {
            showToast('设置保存成功');
        } else {
            showToast('保存失败：' + result.message, 'error');
        }
    } catch (error) {
        console.error('Error saving settings:', error);
        showToast('保存设置失败', 'error');
    }
}

// 渲染用户列表
function renderUsers(users) {
    const container = document.querySelector('[data-section="users"]');
    if (!container) return;

    container.innerHTML = users.map(user => `
        <div class="col">
            <div class="card h-100 bg-dark border-secondary">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <img src="${user.avatar || '/static/images/avatar.png'}" class="rounded-circle me-3" width="48" height="48" alt="${user.username}">
                        <div>
                            <div class="d-flex align-items-center">
                                <h6 class="mb-0 me-2">${user.username}</h6>
                                <i class="fas fa-${user.gender === 'male' ? 'mars' : 'venus'} text-white"></i>
                            </div>
                            <small class="text-muted">${user.grade}</small>
                        </div>
            </div>
                    <div class="d-flex justify-content-end">
                        <button class="btn btn-link text-white p-1 me-2" onclick="editUser(${user.id})" title="编辑">
                    <i class="fas fa-edit"></i>
                </button>
                        <button class="btn btn-link text-danger p-1" onclick="deleteUser(${user.id})" title="删除">
                    <i class="fas fa-trash-alt"></i>
                </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 编辑用户
function editUser(userId) {
    fetch(`/api/users/${userId}`)
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                const user = result.data;
                // 填充表单
                document.getElementById('userName').value = user.username;
                document.querySelector(`input[name="gender"][value="${user.gender}"]`).checked = true;
                document.getElementById('userGrade').value = user.grade;
                document.getElementById('avatarPreview').src = user.avatar || '/static/images/avatar.png';
                
                // 添加用户ID到表单
                const form = document.getElementById('userForm');
                form.dataset.userId = userId;
                
                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('userEditModal'));
                modal.show();
            }
        })
        .catch(error => {
            console.error('Error loading user:', error);
            showToast('加载用户信息失败', 'error');
        });
}

// 删除用户
function deleteUser(userId) {
    if (confirm('确定要删除这个用户吗？此操作不可恢复。')) {
        fetch(`/api/users/${userId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                showToast('用户已删除');
                loadUsers(); // 重新加载用户列表
            } else {
                showToast('删除失败：' + result.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error deleting user:', error);
            showToast('删除用户失败', 'error');
        });
    }
}

// 显示提示消息
function showToast(message, type = 'success') {
    const toastContainer = document.createElement('div');
    toastContainer.style.position = 'fixed';
    toastContainer.style.top = '20px';
    toastContainer.style.right = '20px';
    toastContainer.style.zIndex = '9999';
    
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    const icon = type === 'success' ? 'check-circle' : 'exclamation-circle';
    const colorClass = type === 'success' ? 'text-success' : 'text-danger';
    
    toast.innerHTML = `
        <div class="toast-header">
            <i class="fas fa-${icon} ${colorClass} me-2"></i>
            <strong class="me-auto">提示</strong>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            ${message}
        </div>
    `;
    
    toastContainer.appendChild(toast);
    document.body.appendChild(toastContainer);
    
    const bsToast = new bootstrap.Toast(toast, {
        autohide: true,
        delay: 3000
    });
    
    bsToast.show();
    
    toast.addEventListener('hidden.bs.toast', function() {
        document.body.removeChild(toastContainer);
    });
} 